<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div class="wrap">
        <p>用户名：<input type="text" id="user"></p>
        <p>密&emsp;码：<input type="text" id="pwd"></p>
        <p><input id="btn" type="submit"></p>
    </div>
</body>
<script>

    var userInp = document.querySelector("#user");
    var pwdInp = document.querySelector("#pwd");
    var btn = document.querySelector("#btn");

    // var cookie = document.cookie;
    // if (cookie) {
    //     // var dataArr = cookie.split("; ");
    //     var dataArr = cookie.split(";");
    //     for (var i = 0; i < dataArr.length; i++) {
    //         var item = dataArr[i].trim();
    //         // console.log(item);
    //         var key = item.split("=")[0];
    //         var value = item.split("=")[1];
    //         console.log(key, value);
    //         if (key == "user") {
    //             userInp.value = value;
    //         }
    //         if (key == "pwd") {
    //             pwdInp.value = value;
    //         }

    //     }
    // }


    btn.onclick = function () {
        var user = userInp.value;
        var pwd = pwdInp.value;


        setCookie("user", user, 7);
        setCookie("pwd", pwd, 7);
        // var date = new Date();
        // date.setDate(date.getDate() + 7);
        // document.cookie = "user=" + user + ";expires=" + date + ";path=/";
        // document.cookie = "pwd=" + pwd + ";expires=" + date + ";path=/";
    }


    function setCookie(name, val, day, path = "/") {
        var date = new Date();
        date.setDate(date.getDate() + day);
        document.cookie = name + "=" + val + ";expires=" + date + ";path=" + path;
    }

    function getCookie(name) {
        var cookie = document.cookie;
        if (cookie) {
            // var dataArr = cookie.split("; ");
            var dataArr = cookie.split(";");
            for (var i = 0; i < dataArr.length; i++) {
                var item = dataArr[i].trim();
                // console.log(item);
                var key = item.split("=")[0];
                var value = item.split("=")[1];
                // console.log(key, value);
                if (key == name) {
                    return value;
                }

            }
        }
    }
</script>
</html>